/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.TCC_NOVO.client.componente;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RichTextArea;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.ObjectFieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.HtmlEditor;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.event.TextFieldListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import com.gwtext.client.widgets.layout.ColumnLayout;
import com.gwtext.client.widgets.layout.ColumnLayoutData;
import com.gwtext.client.widgets.layout.FormLayout;
import com.gwtext.client.widgets.layout.RowLayoutData;
import java.util.ArrayList;
import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.comando.Comando;
import org.TCC_NOVO.client.modelo.Slide;

/**
 *
 * @author Emerson
 */
public class FrStoryBoards extends Panel{


    private final GWTServiceAsync controller;
    FormPanel formPanel;
    HtmlEditor htmlEditor;
//    RichTextArea htmlEditor;
    TextArea comentario;
    TextField referencia;
    Button botaoSalvar;
    Button botaoNovo;
    Button botaoExcluir;
    Button botaoSalvarTemplate;
    Button botaoVisualizarTemplate;
    GridPanel gridSlide;
    Store storeSlide;
    RecordDef recordDefSlide;
    ArrayList<Slide> itensRemovidosSlideRoteiro = new ArrayList<Slide>();
    boolean dadosAlterados = false;
    DadosAlterados eventoDadosAlterados = null;
    private Record linhaAtual = null;
    private Record linhaCarregar = null;

    public FrStoryBoards(GWTServiceAsync controller) {
        this.controller = controller;
        this.eventoDadosAlterados = new DadosAlterados();
        this.setTitle("Slides");
        this.setLayout(new ColumnLayout());
        this.setBorder(false);
        this.add(getPanelSlide(), new ColumnLayoutData(0.20));
        this.add(getPanelEdicao(), new ColumnLayoutData(0.80));
    }

    private Panel getPanelEdicao(){
        Panel panelEdicao = new Panel();
        panelEdicao.setFrame(true);
        panelEdicao.add(getPanelNorth());
        panelEdicao.add(getPanelEditor());
        return panelEdicao;
    }

     private Panel getPanelEditor(){
        Panel ObjetTab = new Panel();
        ObjetTab.setFrame(true);
        ObjetTab.setLayout(new FormLayout());
        ObjetTab.setPaddings(1);

        referencia = new TextField("Título", "referencia");
        referencia.setWidth(210);
        referencia.addListener(eventoDadosAlterados);
        ObjetTab.add(referencia);

        htmlEditor = new HtmlEditor("Slide", "texto");
        htmlEditor.addListener(eventoDadosAlterados);

        htmlEditor.setSize(750, 300);
        ObjetTab.add(htmlEditor, new RowLayoutData(300));

        comentario = new TextArea("Comentário");
        comentario.addListener(eventoDadosAlterados);
        comentario.setSize(750, 50);
        ObjetTab.add(comentario, new RowLayoutData(50));
        return ObjetTab;
    }

     private Panel getPanelSlide(){
       recordDefSlide = new RecordDef(new FieldDef[]{
            new IntegerFieldDef("id"),
            new StringFieldDef("referencia"),
            new StringFieldDef("conteudo"),
            new StringFieldDef("comentario"),
            new ObjectFieldDef("slide")
        });

        storeSlide = new Store(recordDefSlide);

        gridSlide = new GridPanel();
        gridSlide.setStore(storeSlide);

        ColumnConfig[] columnsObj = new ColumnConfig[]{
            new ColumnConfig("Slides", "referencia", 170, true)
        };

        ColumnModel columnModel = new ColumnModel(columnsObj);
        gridSlide.setColumnModel(columnModel);
        gridSlide.setFrame(true);
        gridSlide.setStripeRows(true);
        gridSlide.setSize(170, 540);
        gridSlide.addGridCellListener(new GridCellListenerAdapter() {
            @Override
            public void onCellDblClick(GridPanel grid, int rowIndex, int colIndex, EventObject e) {
                linhaCarregar = gridSlide.getSelectionModel().getSelected();
                if(dadosAlterados && linhaAtual != null){
                    MessageBox.confirm("Salvar", "Deseja salvar o slide atual?",
                        new MessageBox.ConfirmCallback() {
                            public void execute(String btnID) {
                                if (btnID.equals("yes")) {
                                   salvarSlide(linhaAtual);
                                }
                                dadosAlterados = false;
                                carregarCampos(linhaCarregar);
                            }
                        });
                }else{
                    carregarCampos(linhaCarregar);
                }
                linhaAtual = gridSlide.getSelectionModel().getSelected();
            }
        });
        return gridSlide;
    }

     private void carregarCampos(Record linha){
        referencia.setValue(linha.getAsString("referencia"));
        htmlEditor.setValue(linha.getAsString("conteudo"));
        comentario.setValue(linha.getAsString("comentario"));
     }

     private Panel getPanelNorth(){
         Panel panelBotoes = new Panel();
         panelBotoes.setPaddings(0);
         panelBotoes.setMargins(0);
         panelBotoes.setButtonAlign(Position.LEFT);
         panelBotoes.setHeight(25);
         panelBotoes.setFrame(true);
         panelBotoes.setLayout(new FormLayout());
         botaoNovo = new Button();
         botaoNovo.setText("Novo");
         botaoNovo.setTooltip("Novo");
         botaoNovo.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                limparSlide();
                linhaAtual = null;
            }
         });
         panelBotoes.addButton(botaoNovo);

         botaoSalvar = new Button();
         botaoSalvar.setText("Salvar");
         botaoSalvar.setTooltip("Salva slide no grid o slide");
         botaoSalvar.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (referencia.getText().equals("")){
                    MessageBox.alert("O título do slide é obrigatório!");
                }else{
                    salvarSlide(linhaAtual);
                    limparSlide();
                    linhaAtual = null;
                }
            }
         });

         panelBotoes.addButton(botaoSalvar);

         botaoExcluir = new Button();
         botaoExcluir.setText("Excluir");
         botaoExcluir.setTooltip("Excluir slide da grid");
         botaoExcluir.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (gridSlide.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                }else {
                    MessageBox.confirm("Confirmação de Exclusão", "Deseja Realmente Remover o Registro?", new MessageBox.ConfirmCallback(){
                    public void execute(String btnID){
                        if (btnID.equals("yes")){
                            removeSlide();
                            linhaAtual = null;
                        }
                    }});
                }
            }
        });

         panelBotoes.addButton(botaoExcluir);

         final AsyncCallback callbackIncluirTemplate = new AsyncCallback() {
            @Override
            public void onSuccess(Object result) {
                MessageBox.alert("Template salvo!");
            }
            @Override
            public void onFailure(Throwable caught) {
               MessageBox.alert("Erro ", caught.getMessage()); }
        };


         botaoSalvarTemplate = new Button();
         botaoSalvarTemplate.setText("Salvar Template");
         botaoSalvarTemplate.setTooltip("Salvar Template");
         botaoSalvarTemplate.addListener(new ButtonListenerAdapter(){
            @Override
            public void onClick(Button button, EventObject e){
                if (referencia.getText().equals("")){
                    MessageBox.alert("O título do slide é obrigatório!");
                }else{
                    Slide slide = getSlideForm();
                    controller.adicionarTemplateSlide(slide, callbackIncluirTemplate);
                }
            }
        });
        panelBotoes.addButton(botaoSalvarTemplate);

        botaoVisualizarTemplate = new Button();
         botaoVisualizarTemplate.setText("Visualizar Templates");
         botaoVisualizarTemplate.setTooltip("Visualizar Templates");
         botaoVisualizarTemplate.addListener(new ButtonListenerAdapter(){
            @Override
            public void onClick(Button button, EventObject e){
                FrTemplateSlide templates = new FrTemplateSlide(controller, new CarregarTemplateSelecionado());
                templates.show();
            }
        });
        panelBotoes.addButton(botaoVisualizarTemplate);
        return panelBotoes;
     }

     public String getTextoEditor(){
         return htmlEditor.getValueAsString();
     }

     public void focusEditorHtml(){
         htmlEditor.focus();
     }

     public Slide getSlideForm(){
        Slide slide = new Slide();
        slide.setReferencia(referencia.getText());
        slide.setComentario(comentario.getText());
        slide.setConteudo(htmlEditor.getValueAsString());
        return slide;
    }

    public void limparSlide(){
        comentario.setValue("");
        htmlEditor.setValue("");
        referencia.setValue("");
    }

    public ArrayList<Slide> getListaSlides(){
        ArrayList<Slide> arrayAtivSlide = new ArrayList<Slide>();
        for (int i = 0; i < storeSlide.getCount(); ++i) {
            Slide slide = new Slide();
            slide.setId(storeSlide.getAt(i).getAsInteger("id"));
            slide.setReferencia(storeSlide.getAt(i).getAsString("referencia"));
            slide.setConteudo(storeSlide.getAt(i).getAsString("conteudo"));
            slide.setComentario(storeSlide.getAt(i).getAsString("comentario"));
            arrayAtivSlide.add(slide);
        }
        return arrayAtivSlide;
    }

    public void addRecordSlide(Slide slide){
        Object[] rowData = new Object[]{
         slide.getId(),
         slide.getReferencia(),
         slide.getConteudo(),
         slide.getComentario(),
         slide,
        };
        Record recordLoc = recordDefSlide.createRecord(slide.getId()+"", rowData);
        storeSlide.add(recordLoc);
    }

    private void removeSlide(){
        Slide slide = new Slide();
        slide.setId(gridSlide.getSelectionModel().getSelected().getAsInteger("id"));
        itensRemovidosSlideRoteiro.add(slide);
        storeSlide.remove(gridSlide.getSelectionModel().getSelected());
    }

    private void salvarSlide(Record linha){
        Slide slide = getSlideForm();
        //se não tiver nenhum item do grid selecionado então adiciona no grid
        if (linha == null){
            addRecordSlide(slide);
        }else{//senão altera grid selecionado
            linha.set("referencia", slide.getReferencia());
            linha.set("conteudo", slide.getConteudo());
            linha.set("comentario", slide.getComentario());
            linha.set("slide", slide);
            gridSlide.getSelectionModel().deselectRange(0,50);
        }
    }

    public ArrayList<Slide> getItensRemovidos(){
        return itensRemovidosSlideRoteiro;
    }

    public void loadRecord(ArrayList<Slide> listaSlide){
        //preenche o grid com as atividades daquele roteiro
        for (Slide slide: listaSlide) {
            addRecordSlide(slide);
        }
    }

    public Store getListaSlide(){
        return storeSlide;
    }


    public class CarregarTemplateSelecionado implements Comando{

        @Override
        public void executar(Object objeto) {
            Slide template = (Slide)objeto;
            referencia.setValue(template.getReferencia());
            htmlEditor.setValue(template.getConteudo());
            comentario.setValue("");
        }

    }

    private class DadosAlterados extends TextFieldListenerAdapter{

        @Override
        public void onChange(Field field, Object newVal, Object oldVal) {
            dadosAlterados = true;
        }

    }
}
